from django.db import models
from django.utils import timezone

class Stock(models.Model):
    """股票基本信息模型"""
    code = models.CharField(max_length=10, unique=True, verbose_name="股票代码")
    name = models.CharField(max_length=50, verbose_name="股票名称")
    industry = models.CharField(max_length=50, null=True, blank=True, verbose_name="所属行业")
    market = models.CharField(max_length=20, null=True, blank=True, verbose_name="交易所")
    is_active = models.BooleanField(default=True, verbose_name="是否活跃")
    created_at = models.DateTimeField(auto_now_add=True, verbose_name="创建时间")
    updated_at = models.DateTimeField(auto_now=True, verbose_name="更新时间")

    class Meta:
        verbose_name = "股票"
        verbose_name_plural = "股票"
        ordering = ['code']

    def __str__(self):
        return f"{self.code} - {self.name}"

class StockPrice(models.Model):
    """股票价格历史数据模型"""
    stock = models.ForeignKey(Stock, on_delete=models.CASCADE, related_name='prices', verbose_name="股票")
    date = models.DateField(verbose_name="日期")
    open_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="开盘价")
    close_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="收盘价")
    high_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="最高价")
    low_price = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="最低价")
    volume = models.BigIntegerField(verbose_name="成交量")
    amount = models.DecimalField(max_digits=20, decimal_places=2, null=True, blank=True, verbose_name="成交额")
    
    class Meta:
        verbose_name = "股票价格"
        verbose_name_plural = "股票价格"
        ordering = ['-date']
        unique_together = ['stock', 'date']

    def __str__(self):
        return f"{self.stock.code} - {self.date}"